<template>
  <div id="index" ref="appRef">
    <div class="bg">
      <dv-loading v-if="loading">Loading...</dv-loading>
      <!-- 第一行 标题-->
      <div v-else class="host-body">
        <div class="d-flex jc-center">
          <div>
            <dv-decoration-10 class="dv-dec-10" />
            <div class="react-left">
                <span class="text">
                  当前节点：XX:XX:XX:XX:XX:XX
                </span>
            </div>
          </div>
          <div class="d-flex jc-center">
            <dv-decoration-8 class="dv-dec-8" :color="['#568aea', '#000000']" />
            <div class="title">
              <span class="title-text">{{ title }}</span>
              <dv-decoration-6
                class="dv-dec-6"
                :reverse="true"
                :color="['#50e3c2', '#67a1e5']"
              />
            </div>
            <dv-decoration-8
              class="dv-dec-8"
              :reverse="true"
              :color="['#568aea', '#000000']"
            />
          </div>
          <div>
            <dv-decoration-10 class="dv-dec-10" />
            <div class="react-right">
              <span class="text">
                {{ timeInfo.dateYear }}
                {{ timeInfo.dateDay }}
                {{ timeInfo.dateWeek }}
              </span>
            </div>
          </div>

        </div>
        <div class="body-box">
          <div class="content-box">
            <div>
              <dv-border-box-12>
                <!--  -->
                <dv-table :table="onlineUserTable" />
              </dv-border-box-12>
            </div>
            <div>
              <!-- 中间 -->
              <echarts-map-node/>
            </div>
            <div>
              <div>
                <dv-border-box-12>
                  <!-- -->
                  <echarts-bar-scroll  :chartBarRanking="flowRanking"/>
                </dv-border-box-12>
              </div>
              <div>
                <dv-border-box-12>
                  <!-- -->
                  <echarts-line-scroll :chartBarRanking="packetRanking"/>
                </dv-border-box-12>
              </div>

            </div>
          </div>
          <div class="bototm-box">
            <dv-border-box-12>
              <!-- -->
              <echarts-pie-dv-digital :numerical="userTotal"/>
            </dv-border-box-12>
            <dv-border-box-12>
              <!-- -->
              <echarts-bar-line-scroll :chartData="flowScroll"/>
            </dv-border-box-12>
            <dv-border-box-12>
              <!--  -->
              <dv-table-warn/>
            </dv-border-box-12>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  reactive,
  onMounted,
  onBeforeUnmount, toRefs,
} from 'vue'

import { formatTime } from '@/utils'
import { title, subtitle, WEEK } from '@/constant'
import useDraw from '@/utils/useDraw'
import EchartsMapNode from '@/views/echarts/map/node/index.vue'
import DvTableWarn from '@/views/datav/table/warn/index.vue'

import DvTable from '@/views/datav/table/index.vue'
import EchartsPieDvDigital from '@/views/echartsdv/piedigital/index.vue'
import EchartsBarScroll from '@/views/echarts/bar/scroll/index.vue'
import EchartsLineScroll from '@/views/echarts/line/scroll/index.vue'
import EchartsBarLineScroll from '@/views/echarts/barline/scroll/index.vue'
import {api} from "@/axios/api";
export default defineComponent({
  components: {
    EchartsMapNode,
    EchartsBarLineScroll,
    EchartsPieDvDigital,
    DvTableWarn,
    EchartsBarScroll,
    EchartsLineScroll,
    DvTable,
  },
  setup() {
    // * 加载标识
    const loading = ref<boolean>(true)
    // * 时间内容
    const timeInfo = reactive({
      setInterval: 0,
      dateDay: '',
      dateYear: '',
      dateWeek: ''
    })
    // * 适配处理
    const { appRef, calcRate, windowDraw, unWindowDraw } = useDraw()

    // methods
    // todo 处理 loading 展示
    const cancelLoading = () => {
      setTimeout(() => {
        loading.value = false
      }, 500)
    }

    // todo 处理时间监听
    const handleTime = () => {
      timeInfo.setInterval = setInterval(() => {
        const date = new Date()
        timeInfo.dateDay = formatTime(date, 'HH: mm: ss')
        timeInfo.dateYear = formatTime(date, 'yyyy-MM-dd')
        timeInfo.dateWeek = WEEK[date.getDay()]
      }, 1000)
    }
    const nodeName ="XXX节点";
    /***********************************************/
    const timerInterval = reactive({
      interval: 0,
      times: 60000,
    })

    // 定义响应式数据 data
    const state= reactive({
      onlineUserTable: {
        title: "在线用户",
        width: "350px",
        height: "770px",
        bgHeight: "740px",
        tbHeight: "700px",
        config: {
          header: ['用户名', 'IP地址'],
          data: [],
          rowNum: 15, //表格行数
          headerHeight: 35,
          columnWidth: [50, 70, 230],
          index: true,
          align: ['center']
        }
      },userTotal: {
        title: "在线率",
        digitals: [],
        pie:{
          width: "350px",
          height: "100px",
          xData: ['异常用户','离线用户','在线用户'],
          seriesColor: [ '#EB6841','#828c9d','#1370fb'],
          seriesData:[{ value: 0, name: '异常用户'},{value: 0, name: '离线用户' },{value: 0, name: '在线用户' }],
        }
      },flowRanking: {
        title: "主干节点流量信息",
        width: "350px",
        bar:{
          category:[],
          series:[{name:"正常流量",data:[]},{name:"异常流量",data:[]}],
        }
      },packetRanking: {
        title: "主干节点包信息",
        width: "350px",
        line:{
          category:[],
          series:[{name:"正常包",data:[]},{name:"异常包",data:[]}],
        }
      },flowScroll: {
        title: "全域流量信息",
        height: "230px",
        category:[],
        series:[{name:"带宽",data:[]},{name:"正常流量",data:[]},{name:"总流量",data:[]}],
      }

    });

    // 定义方法
    const methods = {
      async changeOnlineUser() {
        await api.nidtga.online().then((res: any) => {
          if (res && res.data && res.data.code === 0) {
            if (res.data.data && res.data.data.length > 0) {
              //console.log("mock Online User :" + res.data.data.length)
               res.data.data.forEach((user,index) => {
                if(user){
                  let udata = []
                  if(index % 2 ==0){
                    udata =  [user.name, "<span  class='colorBlue'>"+user.ipv4+"</span>"]
                  }else{
                    udata =  [user.name, "<span  class='colorGrass' title='"+user.ipv6+"'>"+user.ipv6+"</span>"]
                  }
                  state.onlineUserTable.config.data.push(udata)
                }
              })
            }
          }
        })
      }, async changeUserTotal() {
        await api.nidtga.userTotal().then((res: any) => {
          if (res && res.data.code === 0) {
            if (res.data.total) {
              //console.log("mock User total:" + res.data.total)

              let pieData = reactive({
                newList:[]
              })

              const online = {
                text: '在线用户数量',
                icon: 'icon-diagnose',
                config: {
                  number: [ res.data.online],
                  toFixed: 0,// 小数点位数
                  content: '{nt}',
                  style: {
                    fontSize: 24,
                    fill: '#1370fb' //
                  }
                }
              }
              const total = {
                text: '总用户数量',
                icon: 'icon-tongji2',
                config: {
                  number: [ res.data.total],
                  toFixed: 0,// 小数点位数
                  content: '{nt}',
                  style: {
                    fontSize: 24,
                    fill: '#3de7c9' //
                  }
                }
              }

              const abnormal = {
                text: '异常用户数量',
                icon: 'icon-early-warning',
                config: {
                  number: [ res.data.abnormal],
                  toFixed: 0,// 小数点位数
                  content: '{nt}',
                  style: {
                    fontSize: 24,
                    fill: '#EB6841' //
                  }
                }
              }
              const offline = {
                text: '离线用户数量',
                icon: 'icon-clouddownload',
                config: {
                  number: [ res.data.offline],
                  toFixed: 0,// 小数点位数
                  content: '{nt}',
                  style: {
                    fontSize: 24,
                    fill: '#828c9d' //
                  }
                }
              }
              state.userTotal.digitals[0] = online
              state.userTotal.digitals[1] = total
              state.userTotal.digitals[2] = abnormal
              state.userTotal.digitals[3] = offline

              state.userTotal.pie.seriesData[0].value = res.data.abnormal
              state.userTotal.pie.seriesData[1].value = res.data.offline
              state.userTotal.pie.seriesData[2].value = res.data.online
            }
          }
        })
      },
      async changeNodesFlowPacket() {
        await api.nidtga.nodesFlowPacket().then((res: any) => {
          if (res && res.data && res.data.code === 0) {
            if (res.data.data && res.data.data.length > 0) {
              res.data.data.forEach((node,index) => {
                if(node){
                  state.flowRanking.bar.category[index] = node.name
                  // 正常流量
                  state.flowRanking.bar.series[0].data[index]=node.normalFlow
                  // 异常流量
                  state.flowRanking.bar.series[1].data[index]=node.abnormalFlow

                  /*****************/
                  state.packetRanking.line.category[index] = node.name
                  // 正常包
                  state.packetRanking.line.series[0].data[index]=node.normalPacket
                  // 异常包
                  state.packetRanking.line.series[1].data[index]=node.abnormalPacket
                }
              })
            }
          }
        })
      },
      async changeNodesAllFlow() {
        await api.nidtga.nodesAllFlow().then((res: any) => {
          if (res && res.data && res.data.code === 0) {
            if (res.data.data && res.data.data.length > 0) {
              //console.log("mock nodes flow packet :" + res.data.data.length)
              res.data.data.forEach((node,index) => {
                if(node){
                  state.flowScroll.series[0].data[index]=node.bandwidth
                  state.flowScroll.category[index] = node.nodeName
                  // send流量
                  state.flowScroll.series[1].data[index]=node.send
                  // all流量
                  state.flowScroll.series[2].data[index]=node.receive
                }
              })
            }
          }
        })
      },
      async initData() {
        await methods.changeOnlineUser()
        await methods.changeUserTotal()
        await methods.changeNodesFlowPacket()
        await methods.changeNodesAllFlow()
      },
      async changeTiming() {
        timerInterval.interval = setInterval(() => {
          methods.changeOnlineUser()
          methods.changeUserTotal()
          methods.changeNodesFlowPacket()
          methods.changeNodesAllFlow()
        }, timerInterval.times)
      },
    }


    // 生命周期
    onMounted(() => {
      cancelLoading()
      handleTime()
      // todo 屏幕适应
      windowDraw()
      calcRate()
      methods.initData()
      methods.changeTiming()
    })

    onBeforeUnmount(() => {
      unWindowDraw()
      clearInterval(timeInfo.setInterval)
    })


    // return
    return {
      loading,
      timeInfo,
      appRef,
      title,
      subtitle,
      nodeName,
      ...toRefs(state),
      ...methods,
    }
  }
})
</script>

<style lang="scss" scoped>
@import '@/assets/scss/index.scss';
</style>
